/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PenggunaUpdatePanel.java
 *
 * Created on Oct 22, 2014, 4:04:25 PM
 */
package com.ivanbiz.ui;

import com.ivanbiz.dao.GroupsDAO;
import com.ivanbiz.dao.PenggunaDAO;
import com.ivanbiz.dao.impl.GroupsDAOImpl;
import com.ivanbiz.dao.impl.PenggunaDAOImpl;
import com.ivanbiz.model.Groups;
import com.ivanbiz.model.Pengguna;
import com.ivanbiz.service.JTextFieldLimit;
import com.ivanbiz.service.MD5;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JDialog;
import javax.swing.JOptionPane;

/**
 *
 * @author IW20149X
 */
public class PenggunaUpdatePanel extends javax.swing.JPanel {

    Pengguna pengguna;
    List<Groups> listGroup;
    JDialog jDialog;

    public PenggunaUpdatePanel(JDialog jDialog) {
        initComponents();
        refreshGroup();
        this.jDialog = jDialog;
        textKode.setText(getGenereateKode());
    }

    public PenggunaUpdatePanel(JDialog jDialog, Pengguna pengguna) {
        initComponents();
        refreshGroup();
        this.jDialog = jDialog;
        textKode.setText(pengguna.getKode());
        textUser.setText(pengguna.getUserName());
        comboGroup.setSelectedItem(pengguna.getGroups().getNama());
        labelPengguna.setText("Ubah Pengguna");
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        labelPengguna = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        textKode = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        textUser = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        comboGroup = new javax.swing.JComboBox();
        jPanel2 = new javax.swing.JPanel();
        buttonSimpan = new javax.swing.JButton();
        buttonBatal = new javax.swing.JButton();

        labelPengguna.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        labelPengguna.setText("Tambah Pengguna Baru");

        jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jLabel2.setText("Kode :");

        textKode.setEditable(false);

        jLabel3.setText("User Name :");

        textUser.setDocument(new JTextFieldLimit(30));

        jLabel4.setText("Group :");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(textKode, javax.swing.GroupLayout.DEFAULT_SIZE, 356, Short.MAX_VALUE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(textUser, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 356, Short.MAX_VALUE)
                    .addComponent(jLabel4)
                    .addComponent(comboGroup, 0, 356, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(textKode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(textUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(comboGroup, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        buttonSimpan.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/ivanbiz/ui/icon/simpan.jpg"))); // NOI18N
        buttonSimpan.setText("Simpan");
        buttonSimpan.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonSimpanActionPerformed(evt);
            }
        });
        jPanel2.add(buttonSimpan);

        buttonBatal.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/ivanbiz/ui/icon/batal.jpg"))); // NOI18N
        buttonBatal.setText("Batal");
        buttonBatal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonBatalActionPerformed(evt);
            }
        });
        jPanel2.add(buttonBatal);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(labelPengguna)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(labelPengguna)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void buttonBatalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonBatalActionPerformed
        this.jDialog.dispose();
    }//GEN-LAST:event_buttonBatalActionPerformed

    private void buttonSimpanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSimpanActionPerformed
        if (pengguna == null) {
            pengguna = new Pengguna();
        }
        pengguna.setKode(textKode.getText());
        pengguna.setUserName(textUser.getText());
        MD5 md5 = new MD5(textUser.getText());
        pengguna.setPassword(md5.asHex());
        pengguna.setGroups(comboGroup.getSelectedIndex() == -1 ? null : listGroup.get(comboGroup.getSelectedIndex()));
        validate(pengguna);
    }//GEN-LAST:event_buttonSimpanActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonBatal;
    private javax.swing.JButton buttonSimpan;
    private javax.swing.JComboBox comboGroup;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JLabel labelPengguna;
    private javax.swing.JTextField textKode;
    private javax.swing.JTextField textUser;
    // End of variables declaration//GEN-END:variables

    private void refreshGroup() {
        try {
            GroupsDAO groupsDAO = new GroupsDAOImpl();
            listGroup = groupsDAO.getAll(Groups.class);
            updateComboGroup();
        } catch (Exception ex) {
            Logger.getLogger(PenggunaUpdatePanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void updateComboGroup() {
        Object data[] = new Object[listGroup.size()];
        int x = 0;
        for (Groups group : listGroup) {
            data[x] = group.getNama();
            x++;
        }
        comboGroup.setModel(new DefaultComboBoxModel(data));
    }

    private void validate(Pengguna pengguna) {
        if (pengguna.getUserName().isEmpty()) {
            JOptionPane.showMessageDialog(this, "User tidak boleh kosong");
        } else if (pengguna.getGroups() == null) {
            JOptionPane.showMessageDialog(this, "Group tidak boleh kosong");
        } else {
            try {
                PenggunaDAO penggunaDAO = new PenggunaDAOImpl();
                penggunaDAO.saveOrUpdate(pengguna);
                this.jDialog.dispose();
            } catch (Exception ex) {
                Logger.getLogger(PenggunaUpdatePanel.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private String getGenereateKode() {
        String kode = null;
        PenggunaDAO penggunaDAO = new PenggunaDAOImpl();
        try {
            kode = penggunaDAO.getLastKode();
            if (!"".equals(kode)) {
                int count = Integer.parseInt(kode);
                count += 1;
                if (count >= 999) {
                    JOptionPane.showMessageDialog(this, "Kode lebih dari 3 digit");
                } else {
                    kode = String.format("%03d", count);
                }
            } else {
                kode = String.format("%03d", 1);
            }
        } catch (Exception ex) {
            Logger.getLogger(PenggunaUpdatePanel.class.getName()).log(Level.SEVERE, null, ex);
        }
        return kode;
    }
}
